const phone_numberInput = document.getElementById('phone_number');
const passwordInput = document.getElementById('password');
const confirmPasswordInput = document.getElementById('confirm-password');
const errorMessagephone_number = document.querySelector('#phone_number + .error-message');
const errorMessagePassword = document.querySelector('#password + .error-message');
const errorMessageConfirmPassword = document.querySelector('#confirm-password + .error-message');

// 手机号格式
phone_numberInput.addEventListener('input', function (event) {
  if (!event.target.validity.valid) {
    errorMessagephone_number.style.display = 'block';
  } else {
    errorMessagephone_number.style.display = 'none';
  }
});

// 密码格式
passwordInput.addEventListener('input', function (event) {
  if (!event.target.validity.valid) {
    errorMessagePassword.style.display = 'block';
  } else {
    errorMessagePassword.style.display = 'none';
  }
});

// 确认密码格式
confirmPasswordInput.addEventListener('input', function () {
  if (confirmPasswordInput.value !== passwordInput.value) {
    errorMessageConfirmPassword.style.display = 'block';
  } else {
    errorMessageConfirmPassword.style.display = 'none';
  }
});
// 点击登录按钮时发送Ajax请求
const registButton = document.getElementById('regist');
registButton.addEventListener('click', function () {
  const phone_number = phone_numberInput.value.trim();
  const password = passwordInput.value.trim();
  const confirm_password = confirmPasswordInput.value.trim();
  if (phone_number !== '' && password !== '') {
    $.ajax({
      type: 'POST',
      url: 'register',
      data: {
        phone_number: phone_number,
        password: password,
        confirm_password: confirm_password
      },
      success: function (body) {
        if (body.code == 200) {  // 登陆成功，跳转到首页
          alert(body.msg)
          window.location.href = 'login.html';
        } else {  // 登录失败，打印提示信息。
          alert(body.msg)
        }
      },
      error: function () {
        console.error('Error: Login request failed');
      }
    });
  }
});